//
//  BLPlayer.swift
//  BLPlayer
//
//  Created by wkun on 2024/7/5.
//

import UIKit
import AVFoundation
import QuickLook
import AVKit

public enum BLPlayerType{
    case avplayer
    case ffmpeg
    case system    //系统的自带的播放器
    
    func toText() -> String {
        if self == .avplayer {
            return "AVPlayer"
        }else if self == .ffmpeg {
            return "ffmpeg"
        }else{
            return "iOS预览"
        }
    }
}

open class BLPlayer: UIViewController{
    
    var ffmpegPlayer: BLFFmpegPlayer?
    var avPlayer: BLSwiftPlayer?
    
    var type: BLPlayerType?
    var url: URL?
    var videoTitle: String?
    var playBeginTime: TimeInterval = 0.0
    
    private let selectBtn = BorderBtn()
    
    //是否人工手动切换播放器
    private var isManualChangePlayer = false
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        
        self.addPlayer()
    }
    
    public override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
    }
    
    
    
    func addPlayer() {
//        self.view.subviews.first?.removeFromSuperview()
//        self.view.subviews.last?.removeFromSuperview()
//        self.children.first?.removeFromParent()
//        
        self.avPlayer?.view.removeFromSuperview()
        self.ffmpegPlayer?.view.removeFromSuperview()
        self.avPlayer?.removeFromParent()
        self.ffmpegPlayer?.removeFromParent()
        
        self.avPlayer = nil
        self.ffmpegPlayer = nil
        
        if type == .avplayer {
            let vc = BLSwiftPlayer()
            self.avPlayer = vc
            vc.playBeginTime = self.playBeginTime
            vc.url = url
            vc.videoTitle = videoTitle
            vc.view.embedIn(self.view)
            self.addChild(vc)
            
            let v = vc.controlView.moreBtn.superview
            self.addMoreBtn(inView: v)
        }else if type == .ffmpeg{
            let vc = BLFFmpegPlayer()
            self.ffmpegPlayer = vc
            vc.playBeginTime = self.playBeginTime
            vc.url = url
            vc.videoTitle = videoTitle
            vc.view.embedIn(self.view)
            self.addChild(vc)
            
            let v = vc.controlView.moreBtn.superview
            self.addMoreBtn(inView: v)
        }else{
        }
    }
    
    func addMoreBtn(inView: UIView?) {
        guard let v = inView else {
            return
        }
        
        selectBtn.font(12).color("#FFF")
        selectBtn.pin(.wh(100, 45)).addTo(v).makeCons { make in
            make.right.equal(0)
            make.centerY.equal(v)
        }
        selectBtn.str(type?.toText())
        selectBtn.addTarget(self, action: #selector(handleChangePlayer), for: .touchUpInside)
    }
    
    @objc func handleChangePlayer() {
        
        func getTitle(type: BLPlayerType) -> Any{
            let ti = type.toText()
            if type == self.type {
                return AttStr(ti).select(.range(0, ti.count)).color("red")
            }else{
                return ti
            }
        }
        
        var totype: BLPlayerType = .avplayer
        if type == .avplayer {
            totype = .ffmpeg
        }
        
        ActionSheet.title("更换播放器为【\(totype.toText())】").action("确认") {
            self.type = totype
            self.addPlayer()
        }.destructive("取消").show(self)
    }
}

private class BorderBtn: UIButton{
    let borderView = UIView()
    override func layoutSubviews() {
        super.layoutSubviews()
        
        if let v = self.titleLabel {
            if borderView.superview == nil {
                borderView.isUserInteractionEnabled = false
                self.insertSubview(borderView, belowSubview: v)
                borderView.border(1.0, "#FFF")
            }
            
            let fr = v.frame
            if fr != .zero {
                let dx: CGFloat = 5.0
                let dy: CGFloat = 3.0
                borderView.frame = .init(x: fr.origin.x-dx, y: fr.origin.y-dy, width: fr.width+2.0*dx, height: fr.height+2.0*dy)
                borderView.radius(borderView.frame.height/2.0)
            }
        }
    }
}

extension BLPlayer{
    public func getPlayTimeLen() -> TimeInterval? {
        if let player = self.ffmpegPlayer {
            return player.player.timeInfo().playback.seconds
        }else if let player = self.avPlayer{
            return player.player.currentTimeInterval
        }
        return nil
    }
    
    public func getTotalTimeLen() -> TimeInterval? {
        if let player = self.ffmpegPlayer {
            return player.player.timeInfo().duration.seconds
        }else if let player = self.avPlayer{
            return player.player.maximumDuration
        }
        return nil
    }
    
    public func play(url: URL, title: String? = nil, from: UIViewController, type: BLPlayerType, isFullScreen: Bool = true, playBeginTime: TimeInterval = 0 ) {
        
        if type == .system {
            // 创建 AVPlayerViewController
            let playerController = AVPlayerViewController()
            
            // 设置视频资源
            playerController.player = AVPlayer(url: url)
            
            // 添加播放器视图
            from.present(playerController, animated: true) {
                // 开始播放
                playerController.player?.play()
            }
        }
        else{
            let vc = self//BLPlayer()
            vc.videoTitle = title
            vc.url = url
            vc.type = type
            vc.playBeginTime = (playBeginTime)
            if isFullScreen {
                vc.modalPresentationStyle = .overFullScreen
            }
            from.present(vc, animated: true)
        }
    }
    
    static public func getPlayerType(url: URL) async -> BLPlayerType {
        var ty = BLPlayerType.ffmpeg
        
        //若没有指定播放器，则自动判断可用的播放器，优先avplayer
        let asset = AVAsset(url: url)
        var isCanPlay = false
        if #available(iOS 16, *) {
            do {
                isCanPlay = try await asset.load(.isPlayable)
            } catch  {
                
            }
        } else {
            // Fallback on earlier versions
            isCanPlay = asset.isPlayable
        }
        
        if isCanPlay {
            ty = .avplayer
        }
        return ty
    }
    
    
    static public func play(url: URL?, title: String? = nil, from: UIViewController, type: BLPlayerType? = nil, isFullScreen: Bool = true ) {
        
        guard let url = url else {
            print("\n\n=== BLPlayer error : 媒体URL为空 ===\n\n")
            return
        }
        
        Task{
            var ty = type
            if type == nil {
                ty = await self.getPlayerType(url: url)
            }
            
            let ctrl = BLPlayer()
            ctrl.play(url: url, title: title, from: from, type: ty!, isFullScreen: isFullScreen)
        }
    }
}
